# -*- coding: utf-8 -*-
"""
Created on Thu Mar 28 20:14:01 2013

@author: nicola
"""

from kelindo.core.musicbrainz import MusicBrainz
from kelindo.core.musicbrainz import SimilarityError
from kelindo.core.musicbrainz import MBError
from kelindo.core.bagofwords import BagOfWords

class MBClassifier(object):
    def __init__(self):
        self.mb = MusicBrainz()
        return
        
        
    def __get_words_from_folder(self, folder):
        source = BagOfWords()
        for word in folder.path.split('/')[-3:]: source.add_string(word)
        for track in folder.tracks:
            for field in ['albumtitle', 'tracktitle', 'trackauthors', 'filename']:
                try:
                    source.add_string(track[field])
                except KeyError:
                    pass
        return source
        
        
    def __get_best_match(self, folder, candidates):
        """ Returns the best match among a set of candidates """
        src = self.__get_words_from_folder(folder)            
        best_match = [0.0, None]
        for candidate in candidates:
            if len(folder.tracks) != len(candidate):
                continue
            
            dst = BagOfWords()
            for track in candidate:
                for field in ['albumtitle', 'albumauthors', 'tracktitle', 'trackauthors']:
                    dst.add_string(track[field])

            similarity = src.similarity(dst)
            if (similarity >= best_match[0]):
                best_match[0] = similarity
                best_match[1] = candidate
                
        if best_match[1] is None:
            raise SimilarityError
        return best_match

        
    def classify(self, folder): 
        """ Classifies a specific folder """
        try:    
            candidates = []
            for MBID in self.mb.get_MBID(folder.get_durations()):
                print MBID
                candidate = self.mb.get_albums(MBID)
                candidates.extend(candidate)
            dist, tracks = self.__get_best_match(folder, candidates)


            # TODO
            
            folder.status = 'MATCH'
        except SimilarityError:
            folder.status = 'NO_MATCH'
        except MBError:
            folder.status = 'NO_MATCH'
        return

            
